<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>BIMsurfer Developer Mode</title>
<link rel="icon" type="image/png" href="../img/application_home.png" />
<link href="../css/apps.css" type="text/css" rel="stylesheet" />
<link href="../css/apiref.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
</head>

<body>

    <canvas></canvas>

    <div id='apirefContainerContainer'>
        <div id='apirefContainer'>
        </div>
    </div>

    <script type="module">
        import {BimSurfer} from "../viewer/bimsurfer.js";
		import {BimServerClient} from "../../bimserverjavascriptapi/bimserverclient.js"
		import {Address} from "./address.js";
		import {Credentials} from "./credentials.js"
        
        var surfer = window.bimSurfer = new BimSurfer();

		var api = new BimServerClient(Address.getApiAddress());
		api.init().then(() => {
			new Credentials(api).getCredentials().then(() => {
                surfer.load({
                    api: api, 
                    roid:65539,
                    domNode:document.querySelector("canvas")
                }).then(generateApiReference).catch(errorHandler);
			});
		});

        function generateApiReference() {

            var oids = Array.from(bimSurfer._bimServerViewer.viewer.viewObjects.keys());
            oids = _.shuffle(oids);
            oids.splice(10);
            oids = "["+oids.join(", ")+"]";
            
            var METHODS = [
                {name:'setVisibility',     args:[{name: "ids", value: oids}, {name: "visible", value:false}]},
                {name:'setVisibility',     args:[{name: "types", value: '["IfcWallStandardCase"]'}, {name: "visible", value:false}]},
                {name:'setSelectionState', args:[{name: "ids", value: oids}, {name: "selected", value:true}]},
                {name:'getSelected', args:[], hasResult: true},
                {name:'setColor', args:[{name: "ids", value: oids}, {name: "color", value:"{r:1, g:0, b:0, a:1}"}]},
                {name:'viewFit', args:[{name: "ids", value: oids}]},
                {name:'setCamera', args:[{name: "fovy", value: "10"}]},
                {name:'getCamera', args:[], hasResult: true},
                {name:'reset', args:[{name: "cameraPosition", value: true}]},
                {name:'reset', args:[{name: "colors", value: true}]},
                {name:'reset', args:[{name: "visibility", value: true}]},
            ];

            var n = document.getElementById('apirefContainer');
            n.innerHTML = "<h2>API reference</h2>";

            METHODS.forEach(function(m, i) {
                n.innerHTML += "<h3>"+m.name+"()</h3>";
                
                var hasNamedArgs = false;
                var args = m.args.map(function(a) {
                    if (a.name) {
                        hasNamedArgs = true;
                        return a.name + ": " + a.value;
                    } else {
                        return a;
                    }
                }).join(", ");
                
                if (hasNamedArgs) {
                    args = "{"+args+"}";
                }
                
                var cmd = "bimSurfer."+m.name+"("+args+");";
                n.innerHTML += "<textarea rows=3 id='code"+i+"' spellcheck=false>"+cmd+"\n</textarea>";
                var exec_statement = "eval(document.getElementById(\"code"+i+"\").value)"
                if (m.hasResult) {
                    n.innerHTML += "Result:<pre id='result"+i+"' />";
                    exec_statement = "document.getElementById(\"result"+i+"\").innerHTML = stringify(" + exec_statement + ").replace(/,/g, \", \")";
                }
                n.innerHTML += "<button onclick='"+exec_statement+"'>run</button>";
            });
            
            const eventHandlers = document.createElement("div");
            const onClickTextArea = document.createElement("textarea");
			onClickTextArea.setAttribute("rows", 10);
			onClickTextArea.style.overflow = "scroll";
            surfer.addSelectedHandler((object) => {
                if (object !== null) {
                    onClickTextArea.value = onClickTextArea.value + "\n" + object.oid + " (" + object.type + ") clicked";
                }
            });
            eventHandlers.appendChild(onClickTextArea);
            n.appendChild(eventHandlers);
        }

        function stringify(x) {
            function pre(v) {
                if (v.BYTES_PER_ELEMENT) {
                    return Array.from(v);
                } else if ((v instanceof Object) && !(v instanceof Array)) {
                    let r = {};
                    Object.keys(v).forEach((k) => {
                        r[k] = pre(v[k]);
                    });
                    return r;
                } else {
                    return v;
                }
            }
            return JSON.stringify(pre(x));
        }

        function errorHandler(message) {
        	console.error(message);
            let canvas = document.getElementsByTagName("canvas")[0];
            let error = document.createElement("div");
            error.className = "error";
            error.innerHTML = `<span>${message}</span>`
            canvas.parentElement.insertBefore(error, canvas);
            canvas.parentElement.removeChild(canvas);
        }
    </script>

</body>
</html>